import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { TableComponent } from '../../../core/common/table.component';
import { User } from '../../../core/auth/user.service';
import { ConfigService } from '../../../core/common/config.service';
import swal from 'sweetalert2';
import { CommonService } from '../../../core/common/common.service';
import { SelectComponent } from '../../../shared/component/ng2-select/select';
import { TranslateService } from '@ngx-translate/core';
@Component({
  selector: 'app-orderquery',
  templateUrl: './orderquery.component.html',
  styleUrls: ['./orderquery.component.scss']
})
export class OrderqueryComponent implements OnInit {
  @ViewChild('cstDetails') public cstDetails: ModalDirective;
  @ViewChild('markWorkEnd') public markWorkEndChild: ModalDirective;
  @ViewChild('showWorkList') public showWorkList: ModalDirective;
  @ViewChild('datePicker') public datePicker;
  @ViewChild('chnlNameSelect') public chnlNameSelect: SelectComponent;
  @ViewChild('orderStateSelect') public orderStateSelect: SelectComponent;
  // 施工单详情信息
  @Input() nodeInfos: any = {
    nodeEqpt: {},
    nodeNetAccess: [],
    pubCloud: {}
  };
  @Input() workListInfo: any = [];
  // 施工单查询条件参数
  public customer: any = {
    chnlId: '',
    custName: '',
    orderState: '0'
  };
  // 施工单提交者的信息
  public userInfo: any = {
    nodeAccount: null,
    nodeAcctPwd: null,
    organizationName: null,
    applianceName: null,
    finishTime: null
  };
  // 物流信息
  public logisticsInfos: any = {
    companyId: null,
    company: null,
    outLogisticsId: null
  };
  // 物流公司列表信息
  public logisticsCompanys: any = [];
  // 判断显示施工单提交或者物流提交表单
  public showWorkOrLogistics = '';
  public showInfo: any = {
    isShow: true,
    msg: '',
    isShowSubErr: true,
    msgSubErr: ''
  };
  public datepickerOpts = {
    autoclose: true,
    required: true,
    todayBtn: 'linked',
    todayHighlight: true,
    assumeNearbyYear: true,
    format: 'yyyy-mm-dd',
    startDate: '2017-04-01',
    endDate: new Date()
  };
  public columns: Array<any> = [
    { title: '', name: 'orderId', sort: false },
    {
      title: '', name: 'details', sort: false, actions: {
        type: 'simple',
        buttons: [
          {
            name: 'check',
            title: '',
            styleClass: 'btn-green btn-outline',
            styleIcon: 'fa fa-pencil',
            action: 'showOrderList'
          }
        ]
      }
    },
    { title: '', name: 'nodeCount', sort: false },
    { title: '', name: 'chnlName', sort: false },
    { title: '', name: 'custName', sort: false },
    { title: '', name: 'prodName', sort: false },
    { title: '', name: 'orderType', sort: false, formatter: this.formatState.bind(this) },
    { title: '', name: 'orderStateName', sort: false, formatter: this.formatState.bind(this) },
    { title: '', name: 'createDate', sort: false }
  ];
  public config: any = {
    paging: true,
    page: 1,
    itemsPerPage: 12,
    maxSize: 5,
    length: '',
    firstText: '|<',
    previousText: '<<',
    nextText: '>>',
    lastText: '>|',
    sorting: { columns: this.columns },
    filtering: { filterString: '' },
    className: ['table', 'table-hover', 'table-striped'],
    api: {
      showOrderList: this.showOrderList.bind(this),
    }
  };
  public resultTable = new TableComponent({ columns: this.columns, config: this.config, itemsPerPage: this.config.itemsPerPage });
  constructor(public user: User, public http: Http, public configService: ConfigService, public commonService: CommonService,
    private translate: TranslateService) {
    this.translate.get('crm.orderquery.tableHeader').subscribe((res: any) => {
      this.columns.forEach((value, index) => {
        if (value.name === 'details') {
          value.actions.buttons[0].title = res.check;
        };
        value.title = res[value.name];
      });
    });
    this.submitQuery();
    // 获取物流公司列表
    this.getLogCompanys();
  }
  ngOnInit() {
    this.resultTable.onChangeTable(null);
    this.initSelectInfo();
  }
  public initSelectInfo(): void {
    this.translate.get('crm.orderquery.stateAndPrompt').subscribe((res: any) => {
      this.orderStateSelect.items = [{ id: '0', text: res.allState }, { id: '2', text: res.working }, { id: '3', text: res.worked }];
      this.commonService.setSelect(this.customer.orderState, this.orderStateSelect, true);
      const chnlName_url = this.configService.get('url') + '?service=ChnlService&method=getAllChnl';
      this.http.post(chnlName_url, null).toPromise().then((data: any) => {
        const selectInfo: any[] = [{ id: '-1', text: res.allChnl }];
        data.json().info.forEach(value => {
          selectInfo.push({ id: value.chnlId, text: value.chnlName });
        });
        this.chnlNameSelect.items = selectInfo;
        this.commonService.setSelect('-1', this.chnlNameSelect, true);
      });
    });
  }
  public onCellClick(data: any): any { }
  // 订单列表获取
  submitQuery(): void {
    try {
      const tab_url = this.configService.get('url') + '?service=OrderService&method=getAllOrderList';
      const chn_id: string = this.customer.chnlId === '-1' ? '' : this.customer.chnlId;
      this.http.post(tab_url,
        {
          'chnlId': chn_id, 'custName': this.customer.custName, 'orderState': this.customer.orderState,
          'pageNum': this.config.page, 'pageSize': this.config.itemsPerPage
        }).toPromise().then(data => {
          const infos = data.json();
          if (infos.code === '0000') {
            this.resultTable.ng2TableData = infos.info.list;
            this.resultTable.onChangeTable(null);
            this.config.length = infos.info.total;
          } else {
            console.log('orderlist_require ERROR***  #code:' + infos.code + '  #info:' + infos.message);
          }
        });
    } catch (e) {
      // TODO handle exception
    }
  }
  // 根据订单获取相关施工单列表
  public showOrderList(evenyInfo: any): void {
    const order_id = evenyInfo.row.orderId;
    try {
      const show_ord_url = this.configService.get('url') + '?service=WorkService&method=getWorkList';
      this.http.post(show_ord_url, { 'orderId': order_id }).toPromise().then(data => {
        const infos = data.json();
        if (infos.code === '0000') {
          this.workListInfo = infos.info;
          this.workListInfo.order_id = order_id;
          if (!evenyInfo.row.canShow) { this.showWorkList.show(); }
        } else {
          console.log('worklist_require ERROR***  #code:' + infos.code + '  #info:' + infos.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    }
  }
  public formatState(value: string): string {
    let color: string;
    this.translate.get('crm.orderquery.stateAndPrompt').subscribe((res: any) => {
      switch (value) {
        case res.new: color = '#FF6860';
          break;
        case res.change: color = '#FB9903';
          break;
        case res.working: color = '#1AACDA';
          break;
        case res.worked: color = '#24B145';
          break;
        default: color = '#333';
      }
    });
    return `<span style="color:${color};">${value}</span>`;
  }
  public operate(): string {
    return '<a class="fa fa-minus" style="cursor:pointer;">123</a>';
  }
  //  注意：当filter要过滤数字、boolean 等等的时候，要重写这个函数，这个不能match
  public operateClick(row): void {
    this.resultTable.ng2TableData = this.resultTable.ng2TableData.filter((item: any) => {
      item['id'] = item['id'] == null ? '' : item['id'];
      return !item['id'].match(row['id']);
    });
    this.resultTable.onChangeTable(this.config);
  }
  // 施工单详情展示
  public onDetail(idInfo: string): void {
    this.nodeInfos = {
      nodeEqpt: {},
      nodeNetAccess: [],
      pubCloud: {}
    };
    try {
      const detail_url = this.configService.get('url') + '?service=WorkService&method=getWorkDetail';
      this.http.post(detail_url, { 'workId': idInfo }).toPromise().then(data => {
        const curData = data.json();
        if (curData.code === '0000') {
          this.nodeInfos = curData.info.newNode;
          this.nodeInfos.isp.wan.ispWidth = this.nodeInfos.isp.wan.ispWidth + ' Mbps';
          this.nodeInfos.bandWidth = this.nodeInfos.bandWidth + ' Mbps';
          this.translate.get('crm.orderquery.month').subscribe((res: any) => {
            this.nodeInfos.billingCycle = this.nodeInfos.billingCycle + ' ' + res;
          });
          this.datePicker.setStartDate(this.nodeInfos.updateTime.split(' ')[0]);
          this.cstDetails.show();
        } else {
          console.log('workdetail_require ERROR***  #code:' + curData.code + '   #info:' + curData.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    }
  }
  // 标记为施工中
  public onMarkBegin(workid: number): void {
    this.translate.get('crm.orderquery.stateAndPrompt').subscribe((res: any) => {
      try {
        const url = this.configService.get('url') + '?service=WorkService&method=changeWorkDoing';
        this.http.post(url, { 'workId': workid }).toPromise().then(data => {
          const dataInfo = data.json();
          if (dataInfo.code === '0000') {
            this.nodeInfos.workStateName = res.working;
            this.nodeInfos.workState = '2';
            this.workListInfo.filter((item: any) => {
              if (item['workId'] === workid) {
                item['workStateName'] = res.working;
                item['workState'] = '2';
              }
            });
          } else {
            this.showInfo.msg = dataInfo.message;
            this.showInfo.isShow = false;
          }
        });
      } catch (e) {
        // TODO handle exception
      }
    });
  }
  // 初始化表单数据
  public resetShowInfo(): void {
    this.showInfo.msg = '';
    this.showInfo.isShow = true;
    this.showInfo.msgSubErr = '';
    this.showInfo.isShowSubErr = true;
    this.showWorkOrLogistics = 'work';
  }
  public dateChecked() {
    const formatTest = /[0-9]{4}-[0-1][0-9]-[0-3][0-9]/;
    if (!formatTest.test(this.datePicker.datepicker[0].value)) {
      this.userInfo.finishTime = '';
    }
  }
  // 标记施工完成
  public onMarkOver(workid: string): void {
    this.translate.get('crm.orderquery.stateAndPrompt').subscribe((res: any) => {
      try {
        const url = this.configService.get('url') + '?service=WorkService&method=completeWork';
        this.http.post(url, {
          'workId': this.nodeInfos.workId, 'nodeId': this.nodeInfos.nodeId, 'custId': this.nodeInfos.custId,
          WORK_ITEM:
          {
            'nodeAccount': this.userInfo.nodeAccount, 'nodeAcctPwd': this.userInfo.nodeAcctPwd, 'finishTime': this.userInfo.finishTime,
            'organizationName': this.userInfo.organizationName, 'applianceName': this.userInfo.applianceName
          }
        }).toPromise().then(data => {
          const dataInfoEnd = data.json();
          if (dataInfoEnd.code === '0000') {
            this.nodeInfos.workStateName = res.worked;
            this.nodeInfos.workState = '3';
            this.workListInfo.filter((item: any) => {
              if (item['workId'] === workid) {
                item['workStateName'] = res.worked;
                item['workState'] = '3';
              }
            });
            this.markWorkEndChild.hide();
            if (dataInfoEnd.info.orderFinish === '1') {
              // 标记施工完成方法1,直接改前台数据
              this.resultTable.ng2TableData.filter((item: any) => {
                if (item['orderId'] === this.nodeInfos.orderId) {
                  item['orderStateName'] = res.worked;
                  item['orderState'] = '3';
                  this.resultTable.onChangeTable(this.config);
                  return;
                }
              });
              // 标记施工完成方法2,请求数据并刷新
              // this.submitQuery();
            }
          } else {
            this.showInfo.msgSubErr = dataInfoEnd.message === '' ? res.unknownError : dataInfoEnd.message;
            this.showInfo.isShowSubErr = false;
          }
        });
      } catch (e) {
        // TODO handle exception
      }
    });
  }
  // 获取物流公司列表
  public getLogCompanys() {
    try {
      const logComp_url = this.configService.get('url') + '?service=TableDictService&method=getDictList';
      this.http.post(logComp_url, { 'code': 'LOGISTICS_TYPE' }).toPromise().then(data => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          dataInfo.info.forEach(element => {
            this.logisticsCompanys.push({ id: element.value, text: element.label });
          });
        } else {
          console.log(dataInfo.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    }
  }
  // 物流操作
  public logOperate(msg) {
    this.showWorkOrLogistics = 'logistics';
    if (msg === 'add') {
      this.logisticsInfos = {
        companyId: null,
        company: null,
        outLogisticsId: null,
      };
    } else {
      this.logisticsInfos = {
        companyId: this.nodeInfos.postInfo.companyId,
        outLogisticsId: this.nodeInfos.postInfo.outLogisticsId,
      };
    }
    this.markWorkEndChild.show();
  }
  // 上传物流信息
  public updataLogInfos() {
    this.logisticsCompanys.forEach(elem => {
      if (elem.id === this.logisticsInfos.companyId) {
        this.logisticsInfos.company = elem.text;
        return;
      }
    });
    this.logisticsInfos.workId = this.nodeInfos.workId;
    this.logisticsInfos.nodeId = this.nodeInfos.nodeId;
    try {
      const uplog_url = this.configService.get('url') + '?service=WorkService&method=nodeLogisticsInfo';
      this.http.post(uplog_url, this.logisticsInfos).toPromise().then(data => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          // 刷新施工单列表
          this.showOrderList({ row: { orderId: this.nodeInfos.orderId, canShow: true } });
          this.markWorkEndChild.hide();
          this.cstDetails.hide();
        } else {
          swal('失败', dataInfo.message, 'error').catch(swal.noop);
        }
      });
    } catch (e) {
      // TODO handle exception
    }
  }

  // 对输入的参数类型进行实时判断判断
  public regularType(name, value) {
    if (name === 'nodeAccount') {
      return value.replace(/[^a-zA-Z]/g, '');
    } else if (name === 'applianceName') {
      return value.replace(/[\u4e00-\u9fa5]/g, '');
    } else if (name === 'outLogisticsId') {
      return value.replace(/[^a-zA-Z0-9]/g, '');
    }
  }
}